const fs = require('fs');
const globby = require('globby');
const matter = require('gray-matter');

function getKey(path){
    return path.split('/')[2]
}

function getGroup(key){
    return key.split('.')[0]
}

//获取md文档的一级标题
function getDocH1Title(content){
    const regex = /^#\s+(.*)$/gm;
    const match = regex.exec(content)
    return match ? match[1] : ""
}

//获取md文档的二级标题
function getDocH2Titles(content){
    const titles = [];
    const regex = /^##\s+(.*)$/gm;
    let match;
    while((match = regex.exec(content)) != null){
        titles.push(match[1])
    }
    return titles;
}

//文档类型
function getDocType(matData){
   
    return matData.type || 'Main'
}

//文档的兼容模式
function getDbMode(matData){
    return matData.mode || 'All'
}

(async () => {
    const paths = await globby('src/tutorial/*.md')
    
    const docs = [...paths].sort().map((path, index) => {
        const content = fs.readFileSync(path).toString();
        const subTitles = getDocH2Titles(content);
        const { data } = matter(content);
        const key = getKey(path);
        return {
            index,
            key,
            group: getGroup(key),
            type: getDocType(data),
            mode: getDbMode(data),
            title: getDocH1Title(content),
            subTitles
        }
    })

    const genrateDir = 'src/genrate';

    try{
        fs.accessSync(genrateDir, fs.constants.F_OK);
    }catch(err){
        fs.mkdirSync(genrateDir)
    }

    const jsonStr = JSON.stringify(docs, null, 2)

    fs.writeFileSync(`${genrateDir}/tutorial.json`, jsonStr)
   
})();